package com.lengxf.redis.redisson;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping
@AllArgsConstructor
public class MyBloomFilter {

    private final RedissonClient redisson;

    private final static String[] arr = {"1", "3", "5", "19", "10086"};

    public static BloomFilter<CharSequence> guavaBloomFilter = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 10, 0.01);

    @PostConstruct
    public void init() {
        RBloomFilter<String> myBloomFilter = redisson.getBloomFilter("myBloomFilter");
        myBloomFilter.tryInit(10, 0.01);
        //redis 数据初始化
        myBloomFilter.add(Arrays.stream(arr).toList());
        // guava数据初始化
        Arrays.stream(arr).forEach(guavaBloomFilter::put);
    }

    @GetMapping("redisBloomFilter")
    public Boolean redisBloomFilter(@RequestParam("key") String key) {
        RBloomFilter<String> myBloomFilter = redisson.getBloomFilter("myBloomFilter");
        boolean contains = myBloomFilter.contains(key);
        if (!contains) {
            myBloomFilter.add(key);
        }
        return contains;
    }

    @GetMapping("guavaBloomFilter")
    public Boolean guavaBloomFilter(@RequestParam("key") String key) {
        boolean contain = guavaBloomFilter.mightContain(key);
        if (!contain) {
            guavaBloomFilter.put(key);
        }
        return contain;
    }

}
